package com.coder520.mamabike.user.controller;


import com.coder520.mamabike.common.constants.Constants;
import com.coder520.mamabike.common.exception.MaMaBikeException;
import com.coder520.mamabike.common.resp.ApiResult;
import com.coder520.mamabike.common.rest.BaseController;
import com.coder520.mamabike.user.entity.LoginInfo;
import com.coder520.mamabike.user.entity.User;
import com.coder520.mamabike.user.entity.UserElement;
import com.coder520.mamabike.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;


    /**
     * @param loginInfo 移动端传来的信息
     * @author 周国伟
     * 移动端登入（注册）
     * @date 2018/11/8 17:09
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ApiResult login(@RequestBody LoginInfo loginInfo) {
        ApiResult<String> resp = new ApiResult<>();
        try {
            String data = loginInfo.getData();
            String key = loginInfo.getKey();
            if (data == null) {
                throw new MaMaBikeException("非法请求");
            }
            String token = userService.login(data, key);
            resp.setData(token);
        } catch (MaMaBikeException e) {
            resp.setMessage(e.getMessage());
            resp.setCode(e.getStatusCode());
            e.printStackTrace();
        } catch (Exception e) {
            log.error("Fail to login", e);
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
            resp.setMessage("内部信息错误");
        }
        return resp;
    }

    /**
     * @author ZhouGuoWei
     * @date 2018/11/18 16:25
     * @Annotation 修改用户昵称
     */
    @RequestMapping("/modifyNickName")
    public ApiResult modifyNickName(@RequestBody User user) {
        ApiResult<String> resp = new ApiResult<>();

        try {
            //通过Token获取用户ID
            UserElement ue = getCurrentUser();
            user.setId(ue.getUserId());
            userService.modifyNickName(user);
            resp.setMessage("跟新成功");
        } catch (MaMaBikeException e) {
            resp.setCode(e.getStatusCode());
            resp.setMessage(e.getMessage());
        }  catch (Exception e) {
            log.error("更新失败",e);
            resp.setMessage("内部错误");
            resp.setCode(Constants.RESP_STATUS_INTERNAL_ERROR);
        }
        return null;
    }

}
